package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    //分页查询频道
    public ResponseResult listByName(ChannelDto dto) {

        //构建分页条件
        IPage<WmChannel> page=new Page<>(dto.getPage(),dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmChannel>query=new LambdaQueryWrapper<>();
        //判断传入的名称不为空,添加频道名称条件
        if (!StringUtils.isEmpty(dto.getName())) {
            query.like(WmChannel::getName,dto.getName());
        }
        IPage<WmChannel> iPage=this.page(page,query);
        //配置通用的分页响应
        PageResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
        return result;
    }

    //频道新增
    public ResponseResult saveChannel(WmChannel wmChannel) {
        //参数校验
        if (wmChannel==null|| StringUtils.isEmpty(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断频道名称是否存在，存在，不允许新增,根据频道名称查询数据数量
        LambdaQueryWrapper<WmChannel> query=new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,wmChannel.getName());
        int count = this.count(query);
        if (count>0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //不存在，允许新增
        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);
        return ResponseResult.okResult();
    }
}
